<template>
<view>
<!-- <component-tag-product-list wx:if='{{productList}}' data="{{productList}}"></component-tag-product-list>  -->

<block v-if="productList.length != 0">
  <view class="product_items3" v-for="(result, index) in productList" :key="index" :data-id="result.productId||result.id" @tap="tolinkUrl">
    <view class="product_items3_promotion_name" v-if="result.tagArray[0]">{{result.tagArray[0]}}</view>
    <image class="product_items3_img" mode="aspectFill" :src="result.imagePath||result.itemIcon + '?x-oss-process=style/preview_200'"></image>
    <view class="product_items3_view1">
      <text class="product_name">{{result.name||result.itemName}}</text>
      <text class="location_name" v-if="result.addTime&&!result.name">添加时间：{{result.addTime||result.addTime}}</text>
      <text class="location_name" v-if="result.longitude>0">{{result.location}}</text>
      <text class="location_name" v-else>{{result.description}}</text>
      <view class="sale_item3" v-if="result.itemSpecialSaleType&&result.itemSpecialSaleType!=0">
        <view class="sale_item3_title" :style="'background:' + defaultColor">
          <text v-if="result.itemSpecialSaleType==1">满减</text>
          <text v-if="result.itemSpecialSaleType==2">买赠</text>
          <text v-if="result.itemSpecialSaleType==3">限购</text>
        </view>
        <view class="sale_item3_value" v-if="result.itemSpecialSaleType==1" :style="'color:' + defaultColor">
          满<text>{{result.itemSpecialSaleValue1}}元</text>减<text>{{result.itemSpecialSaleValue2}}元</text>
        </view>
        <view class="sale_item3_value" v-if="result.itemSpecialSaleType==2" :style="'color:' + defaultColor">
          买<text>{{result.itemSpecialSaleValue1}}</text>赠<text>{{result.itemSpecialSaleValue2}}</text>
        </view>
        <view class="sale_item3_value" v-if="result.itemSpecialSaleType==3" :style="'color:' + defaultColor">
          限购<text>{{result.itemSpecialSaleValue1}}件</text>
        </view>
      </view>
      <text class="location_name">{{result.unitShow}}</text>
      <view class="product_price">
        <text class="price" v-if="result.promotion>0">￥{{result.promotionPrice}}</text>
        <text class="price" v-else>￥{{result.price||result.itemPrice}}</text>
        <text class="price" v-if="result.maxPrice>result.price">-{{result.maxPrice}}</text>
        <text v-if="result.maxPrice<=result.price&&result.tagPrice>result.price" class="tag_price">￥{{result.tagPrice}}</text>
        <!-- <component-price-group data="{{result}}"></component-price-group> -->
      </view>
    </view>
    <view class="to_car3" @click.stop="readyAddCar" :data-product="result.productId||result.id">
      <text class="button" style="font-size:24rpx;background:#ff826e;margin-right:20rpx" @click.stop="removeFavourite" :data-itemId="result.productId">取消收藏</text>
      <text class="button" :style="'font-size:24rpx;background:' + defaultColor" v-if="result.promotion!=0">立即抢购</text>
      <view class="to_car3_text" :style="'background:' + defaultColor + ';font-size:24rpx;'" v-else> 
        <image class="to_car3_icon" src="http://image1.sansancloud.com/xianhua/2019_3/20/10/45/42_450.jpg?x-oss-process=style/preview_120"></image>
        <text>选购</text>
      </view>
    </view>
  </view>
</block>
  <block v-else>
    <view class="noproduct">
      <image mode="widthFix" src="../../static/icons/no-product.png"></image>
      <text>没有相关产品</text>
    </view>
  </block>
<!-- <component is="measure_card2" :setting="minCount" :focusData="productData.productInfo" :measures="productData.measures" :byNowParams="byNowParams" :measurementJson="measurementJson" :type="bindway"></component> -->
</view>
</template>

<script>

export default {
  data() {
    return {
      favouriteList: [],
      productList: [],
      productData: {},
      measurementJson: null,
      byNowParams: {
        productId: '',
        itemCount: 1,
        shopId: '',
        cartesianId: '0',
        chatOrder: '',
        fromSource: '',
        orderType: ''
      },
      MeasureParams: [],
      showCount: false,
      bindway: "",
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },
      haveMeasuresState: false,
      selectTypeData: "",
      minCount: "",
      countGood: "",
      showGuigeType: false,
      setting: "",
      defaultColor: "",
      secondColor: ""
    };
  },
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserVisitList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting,
      defaultColor: getApp().globalData.setting.platformSetting.defaultColor,
      secondColor: getApp().globalData.setting.platformSetting.secondColor
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.favouriteList = [];
    this.listPage.page = 1;
    this.getUserVisitList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;

    if (that.listPage.totalSize > that.listPage.curPage * that.listPage.pageSize) {
      that.listPage.page++;
      this.getUserVisitList();
    }
  },
  methods: {
    /* 删除收藏 */
    removeFavourite: function (e) {
      let that = this; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      let postData = {
        itemId: '',
        favoriteType: '1'
      };
      postData.itemId = e.currentTarget.dataset.itemid;
      console.log("===postData===", postData);
      let customIndex = getApp().globalData.AddClientUrl("/remove_favorite.html", postData, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);

          if (res.data.errcode == '0') {
            console.log("that.data.productList", that.productList);

            for (let i = 0; i < that.productList.length; i++) {
              if (postData.itemId == that.productList[i].productId) {
                console.log("====i====", i, that.productList[i]);
                that.productList.splice(i, 1);
                that.setData({
                  productList: that.productList
                });
              }
            }

            ;
            wx.showToast({
              title: '已取消收藏！',
              image: '/images/icons/tip.png',
              duration: 1000
            });
          }
        },
        fail: function (res) {
          getApp().globalData.loadFail();
        },
        complete: function (res) {
          wx.hideLoading();
        }
      });
    },
    tolinkUrl: function (e) {
      console.log(e.currentTarget.dataset.id); // product_detail.html?productId= 9219;

      var a = "product_detail.html?productId=" + e.currentTarget.dataset.id;
      getApp().globalData.linkEvent(a);
    },
    toProductDetail: function (event) {
      var info = event.currentTarget.dataset.info;
      wx.navigateTo({
        url: '/pages/productDetail/index?id=' + info.itemId + "&addShopId=" + info.shopId
      });
    },

    /* 获取 */
    getUserVisitList: function () {
      let getParam = {};
      getParam.favoriteType = 1;
      getParam.page = this.listPage.page;
      var customIndex = getApp().globalData.AddClientUrl("/get_favorite.html", getParam);
      var that = this; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('-----------get_favorite--------');
          console.log(res.data);
          that.listPage.pageSize = res.data.pageSize;
          that.listPage.curPage = res.data.curPage;
          that.listPage.totalSize = res.data.totalSize;
          let dataArr = that.favouriteList;
          dataArr = dataArr.concat(res.data.result); //  productList: { androidTemplate: "pupu_product_list_one", jsonData: { count: 0}, relateBean:[] }
          //  { androidTemplate: "pupu_product_list_one", relateBean: dataArr, jsonData: { count: dataArr.length, showCard: 1}, relateBean: dataArr}

          if (!res.data.result || res.data.result.length == 0) {
            that.setData({
              favouriteList: [],
              productList: []
            });
          } else {
            that.setData({
              favouriteList: dataArr,
              productList: dataArr
            });
          }

          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    closeZhezhao: function () {
      this.setData({
        showCount: false
      });
    },

    /* 立即购买 */
    buyNow: function (e) {
      console.log("==buyNow==", e);

      if (!getApp().globalData.checkShopOpenTime()) {
        return;
      }

      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      let bindway;

      if (e.currentTarget.dataset.way) {
        bindway = e.currentTarget.dataset.way;
      } else {
        bindway = this.bindway;
      }

      console.log('=======bindway======', bindway);
      this.setData({
        haveMeasuresState: true
      });
      this.setData({
        selectTypeData: this.selectTypeData
      });
      console.log('-----------addtocart----------');
      this.addtocart();
    },
    // 这里是一个自定义方法
    readyAddCar: function (e) {
      let that = this;
      console.log("====readyAddCar=====", e, that.byNowParams);
      let productInfo = e.currentTarget.dataset.product;
      that.productData.productInfo = productInfo;
      that.setData({
        productData: that.productData
      });
      let productId = productInfo.productId || productInfo.id;
      console.log("====productInfo.id=====", productId);
      that.get_product_measureFun(productId);
    },
    subNum: function () {
      if (this.measurementJson.id) {
        this.setData({
          minCount: this.measurementJson.minSaleCount
        });
      } else {
        this.setData({
          minCount: 1
        });
      }

      if (this.byNowParams.itemCount == this.minCount) {
        return;
      }

      this.byNowParams.itemCount--;
      this.setData({
        byNowParams: this.byNowParams
      });
    },
    addNum: function () {
      this.byNowParams.itemCount++;
      this.setData({
        byNowParams: this.byNowParams
      });
    },
    addtocart: function () {
      console.log("===addtocart====");

      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      var params = {
        cartesianId: '',
        productId: '',
        shopId: '',
        count: '',
        type: ''
      };

      if (this.productData.measures.length == 0) {
        params.cartesianId = '0';
      } else {
        params.cartesianId = this.measurementJson.id;
      }

      let productId = this.productData.productInfo.productId || this.productData.productInfo.id;
      console.log("====productInfo.id=====", productId);
      params.productId = productId;
      params.shopId = this.productData.productInfo.belongShopId || this.productData.productInfo.shopId;
      params.count = this.byNowParams.itemCount;
      params.type = 'add';
      console.log('===postParams=====', params);
      this.postParams(params);
    },
    postParams: function (data) {
      console.log("==postParams====");
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('---------------change_shopping_car_item-----------------');
          console.log(res.data);
          wx.hideLoading();

          if (that.bindway == 'cart') {
            that.setData({
              showCount: false
            });
          }

          if (data.productId == 0) {
            console.log('购物车里面的商品数量');
            that.setData({
              countGood: res.data.totalCarItemCount
            });
          } else {
            if (res.data.productId && res.data.productId != 0) {
              if (data.count == 0) {
                console.log('通过加入购物车来确定购物车里面的商品数量');
              } else {
                wx.showToast({
                  title: '加入购物车成功'
                });
              }

              if (!!res.data.totalCarItemCount || res.data.totalCarItemCount == 0) {
                that.setData({
                  countGood: res.data.totalCarItemCount
                });
              }
            } else {
              wx.showToast({
                title: res.data.errMsg,
                image: '/images/icons/tip.png',
                duration: 2000
              });
            }
          }
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 
       规格操作
    */
    //提交规格产品
    submitMeasure: function (id) {
      var that = this;
      let focusProduct = this.MeasureItem;
      let measurementJson = this.measurementJson;
      let data = {};
      data.cartesianId = measurementJson.id;
      data.productId = focusProduct.id;
      data.shopId = focusProduct.belongShopId;
      data.count = 1;
      data.type = 'add';
      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('--------add----------');
          console.log(res.data);
          that.setData({
            showGuigeType: false
          });
        },
        fail: function (res) {
          getApp().globalData.loadFail();
        },
        complete: function () {
          wx.hideLoading();
        }
      });
    },
    //获取规格价格参数
    get_measure_cartesionFun: function () {
      this.setData({
        measurementJson: {
          waitDataState: false
        }
      });
      let productId = this.productData.productInfo.id;
      let postStr = '';

      if (this.MeasureParams.length == 0) {
        this.byNowParams.cartesianId = '0';
        this.setData({
          measurementJson: {
            waitDataState: true
          }
        }); //没有规格时 不需要等待请求

        return;
      }

      for (let i = 0; i < this.MeasureParams.length; i++) {
        postStr += this.MeasureParams[i].value + ',';
      }

      let param = {};
      param.productId = productId;
      param.measureIds = postStr;
      console.log(postStr);
      let customIndex = getApp().globalData.AddClientUrl("/get_measure_cartesion.html", param);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("===measurementJson===", res.data);
          that.byNowParams.cartesianId = res.data.id;
          that.setData({
            measurementJson: res.data
          });
          that.measurementJson.waitDataState = true;
          that.setData({
            measurementJson: that.measurementJson
          });
          that.byNowParams.itemCount = that.measurementJson.minSaleCount;
          that.setData({
            minCount: that.byNowParams.itemCount
          });
          that.setData({
            byNowParams: that.byNowParams
          });
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },
    //获取规格价格参数
    get_product_measureFun: function (id) {
      let that = this;
      let productId = id;
      let customIndex = getApp().globalData.AddClientUrl("/get_product_measures.html", {
        productId: productId
      });
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          let measures = res.data;
          that.productData.measures = measures;
          that.setData({
            productData: that.productData
          });

          if (measures.length == 0) {
            that.addtocart();
          } else {
            that.setData({
              bindway: "cart"
            });
            that.setData({
              showCount: true
            });
            let info = that.productData.productInfo;
            console.log("====info==", info);
            that.byNowParams.productId = info.id;
            that.byNowParams.shopId = info.belongShopId || info.shopId;
            that.byNowParams.orderType = 0;
            that.setData({
              byNowParams: that.byNowParams
            });
            console.log("==byNowParams===", that.byNowParams);
            that.chooseMeasureItem();
          }
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },

    /* 初始化 选规格 */
    chooseMeasureItem: function (event) {
      console.log('----------初始化规格参数-----------', event);
      let that = this;
      let productData = that.productData;
      let focusProduct = productData;
      let selectTypeData = [];

      for (let i = 0; i < focusProduct.measures.length; i++) {
        focusProduct.measures[i].checkedMeasureItem = 0; //初始化选择的数据

        let param = {};
        let selectTypeDataItem = {};
        param.name = focusProduct.measures[i].name;
        param.value = focusProduct.measures[i].productAssignMeasure[0].id;
        selectTypeDataItem.type = focusProduct.measures[i].name;
        selectTypeDataItem.value = focusProduct.measures[i].productAssignMeasure[0].measureName;
        console.log('=====param=====', param);
        that.MeasureParams.push(param);
        selectTypeData.push(selectTypeDataItem);
      }

      that.selectTypeData = selectTypeData;
      console.log('====that.data.selectTypeData======', this.selectTypeData);
      that.setData({
        productData: focusProduct
      });
      console.log('===MeasureParams====', this.MeasureParams);
      that.get_measure_cartesionFun();
    },
    //选择规格小巷的---显示
    radioChange: function (e) {
      let that = this;
      let flag = false;
      console.log("====radioChange=====", e);
      console.log('====that.data.selectTypeData======', that.selectTypeData);

      if (that.selectTypeData) {
        console.log('1111111');

        for (let i = 0; i < that.selectTypeData.length; i++) {
          if (e.currentTarget.dataset.type == that.selectTypeData[i].type) {
            that.selectTypeData.splice(i, 1, e.currentTarget.dataset);
            flag = true;
          }
        }

        if (!flag) {
          that.selectTypeData.splice(that.selectTypeData.length, 1, e.currentTarget.dataset);
          flag = false;
        }
      } else {
        console.log('222222');
        that.selectTypeData = [];
        that.selectTypeData.splice(0, 1, e.currentTarget.dataset);
        that.setData({
          selectTypeData: that.selectTypeData
        });
      }

      console.log('====that.data.selectTypeData======', that.selectTypeData);
      let index = e.currentTarget.dataset.index;
      let indexJson = getApp().globalData.getSpaceStr(index, '-'); //console.log(indexJson)

      let focusItem = that.productData;
      focusItem.measures[indexJson.str1].checkedMeasureItem = indexJson.str2;
      that.setData({
        productData: focusItem
      });
    },
    //选择规格小巷---获取数据
    chooseMeasure: function (e) {
      console.log(e.detail.value);
      let chooseMeasureJson = getApp().globalData.getSpaceStr(e.detail.value, '-');
      console.log(chooseMeasureJson);

      for (let i = 0; i < this.MeasureParams.length; i++) {
        if (this.MeasureParams[i].name == chooseMeasureJson.str1) {
          this.MeasureParams[i].value = chooseMeasureJson.str2;
        }
      }

      this.get_measure_cartesionFun();
    },
    closeGuigeZhezhao: function () {
      this.setData({
        showGuigeType: false
      });
      this.MeasureParams = [];
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>